<template>
  <a-layout class="advert-detail-wrap">
    <a-layout-sider class="menu-list">
      <div class="shop-w">
        <p class="back-link" @click="toBackCampaign" v-if="advertStore.currentLevel === 'campaign'">
          <icon-arrow-left />
          <span v-if="advertStore.currentCampaign">{{ advertStore.currentCampaign.campaignName }}</span>
        </p>
        <p class="back-link" @click="toBackGroup" v-if="advertStore.currentLevel === 'adGroup'">
          <icon-arrow-left />
          <span v-if="advertStore.currentCampaign">{{ advertStore.currentCampaign.campaignName }}</span>
          <span style="color: #000"> / </span>
          <span style="color: #000" v-if="advertStore.currentGroup">{{ advertStore.currentGroup.adGroupName }}</span>
        </p>
        <a-select placeholder="选择店铺" :loading="shopLoading" value-key="id" v-model="shopInfo" :show-extra-options="false" @change="changeShop" @search="handleSearch" allow-search :filter-option="false">
          <a-option v-for="(shop, i) in shopList" :key="i" :value="shop" :label="shop.shopName" />
        </a-select>
      </div>
      <div class="menu-header">
        <div class="flex-c-sb">
          <p class="title">广告活动</p>
          <a-button size="mini" @click="openCreatePage()">
            <template #icon>
              <icon-plus />
            </template>
          </a-button>
        </div>
        <a-input-search v-model="searchCampaignVal" allow-clear style="margin-top: 10px" all placeholder="搜索活动" @change="getMenuList()" @search="getMenuList()" />
      </div>
      <a-tabs v-model:active-key="currentState" @change="getMenuList" size="mini" style="margin-bottom: 10px">
        <a-tab-pane key="enabled" title="已启用" />
        <a-tab-pane key="paused" title="已暂停" />
        <a-tab-pane key="archived" title="已归档" />
      </a-tabs>
      <a-spin :loading="treeLoading" style="width: 100%">
        <a-scrollbar style="height: calc(100vh - 260px); overflow: auto">
          <a-tree v-if="filterTreeData.length" :key="currentState" ref="treeRef" :blockNode="true" size="small" v-model:selected-keys="selectedKeys" v-model:expanded-keys="expandedKeys" :data="filterTreeData" style="padding: 0 10px" @select="chooseNode">
            <template #title="nodeData">
              <p class="tree-name">
                <span v-if="nodeData.level === 1">已{{ AdStatusHandle[nodeData.state] }}</span>
                <span v-else-if="nodeData.level === 2">{{ nodeData.campaignName }}</span>
                <span v-else>{{ nodeData.adGroupName }}</span>
                <span v-if="nodeData.level === 1 || nodeData.level === 2">({{ nodeData.children ? nodeData.children.length : 0 }})</span>
              </p>
            </template>
            <template #extra="nodeData">
              <icon-edit v-if="nodeData.level === 2 && $authPass('campaign.edit')" class="menu-edit" @click="openEditDialog(nodeData)" />
            </template>
          </a-tree>
          <a-empty v-if="!filterTreeData.length && !treeLoading" />
        </a-scrollbar>
      </a-spin>
    </a-layout-sider>
    <a-layout>
      <a-tabs v-model:active-key="activeTabName" size="mini">
        <!-- 广告活动详情才有广告组列表 -->
        <a-tab-pane v-if="advertStore.currentLevel && advertStore.currentLevel == 'campaign'" key="adGroup" title="广告组" />
        <!-- sd广告活动和广告组不显示广告位 -->
        <a-tab-pane v-if="advertStore.currentLevel && advertStore.currentLevel == 'campaign' && advertStore.currentCampaign.adType != 'SPONSORED_DISPLAY'" key="placement" title="广告位" />
        <a-tab-pane key="product" title="广告产品" />
        <!-- sd广告活动不显示关键词和自动广告不显示关键词 -->
        <a-tab-pane key="keyword" v-if="advertStore.currentCampaign.adType != 'SPONSORED_DISPLAY' && advertStore.currentCampaign.targetingType != 'AUTO'" title="关键词" />
        <!-- SP广告的自动投放才有投放列表 -->
        <a-tab-pane key="targeting" v-if="advertStore.currentCampaign.adType == 'SPONSORED_PRODUCTS' && advertStore.currentCampaign.targetingType == 'AUTO'" title="自动投放" />
        <a-tab-pane key="searchWord" title="搜索词" />
        <a-tab-pane key="negativeKeyword" title="否定关键词" />
        <a-tab-pane key="logs" title="操作日志" />
      </a-tabs>
      <div v-if="showDetail">
        <!-- 广告组 -->
        <AdGroupList v-if="activeTabName === 'adGroup'" @update="getMenuList" @updateNode="setDefaultSelectedNode" />
        <!-- 广告产品 -->
        <ProductList v-if="activeTabName === 'product'" />
        <!-- 关键词列表 -->
        <Keyword v-if="activeTabName === 'keyword'" />
        <!-- 广告位 -->
        <PlacementList v-if="activeTabName === 'placement'" />
        <!-- 自动投放 -->
        <TargetingList v-if="activeTabName == 'targeting'" :type="advertStore.currentLevel" />
        <!-- 搜索词 -->
        <SearchWordList v-if="activeTabName == 'searchWord'" :type="advertStore.currentLevel" />
        <!-- 否定关键词 -->
        <NegativeKeywordList v-if="activeTabName == 'negativeKeyword'" :type="advertStore.currentLevel" />
        <!-- 操作日志 -->
        <AdLogList v-if="activeTabName == 'logs'" />
      </div>
    </a-layout>
  </a-layout>
  <!-- 编辑广告活动 -->
  <EditCampaign v-if="showEditDialog" :isShow="showEditDialog" :shop="shopInfo" :currentItem="currentNode" @closed="showEditDialog = false" @success="getMenuList" />
</template>
<script lang="ts">
  export default defineComponent({
    name: 'SPCampaignDetail',
  })
</script>
<script lang="ts" setup>
  import { defineComponent, ref, watch, computed, onActivated } from 'vue'
  import { findShopMarketByParam } from '@/api/system'
  import AdGroupList from './adGroupList.vue'
  import Keyword from './keywordList.vue'
  import ProductList from './productList.vue'
  import PlacementList from './placementList.vue'
  import EditCampaign from './components/editCampaign.vue'
  import NegativeKeywordList from './negativeKeywordList.vue'
  import AdLogList from './adLogList.vue'
  import SearchWordList from './searchWordList.vue'
  import TargetingList from './targetingList.vue'
  import useAdvertStore from '@/store/modules/advert'
  import { useRouter, useRoute } from 'vue-router'
  import { adGroupTreePage } from '@/api/advert'
  import { AdStatusHandle } from '../types'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  onActivated(() => {
    getMenuList()
    getShopList()
    showDetail.value = false
    setTimeout(() => {
      showDetail.value = true
    }, 10)
  })

  const shopLoading = ref(false)
  const originShopList = ref<Array<any>>([])
  const shopList = ref<Array<any>>([])
  const filterTreeData = ref<Array<any>>([])
  const advertStore = useAdvertStore()
  const router = useRouter()
  const showEditDialog = ref(false)
  const showDetail = ref(true)
  const selectedKeys = ref<Array<string | number>>([])
  const expandedKeys = ref<Array<string | number>>([])
  const currentNode = ref({})
  const treeRef = ref()
  const searchCampaignVal = ref()
  const shopInfo = ref()
  const currentLevel = computed(() => advertStore?.currentLevel)
  const activeTabName = ref(currentLevel.value === 'campaign' ? 'adGroup' : 'product')
  const visitedRouteStore = useVisitedRouteStore()
  const route = useRoute()
  const treeLoading = ref(false)
  const currentState = ref(advertStore.currentCampaign.state?.toLowerCase() || 'enabled')
  // 获取菜单列表
  async function getMenuList() {
    if (!advertStore.currentShop?.shopId) return
    treeLoading.value = true
    let res: any = await adGroupTreePage({
      shopId: advertStore.currentShop.shopId,
      campaignId: advertStore.currentCampaign.campaignId,
      searchCampaignName: searchCampaignVal.value,
      state: currentState.value,
      page: 0,
      limit: 200,
    })
    treeLoading.value = false
    let stateDate: Array<any> = res?.data?.[currentState.value] || []
    expandedKeys.value = []
    stateDate.forEach((item: any) => {
      item.level = 2
      item.children = item.adGroupTrees || []
      item.key = item.campaignId + currentState.value
      delete item.adGroupTrees
      item.children.forEach((row: any) => {
        row.level = 3
        row.campaignId = item.campaignId
        row.campaignName = item.campaignName
        row.key = row.adGroupId + item.campaignId + currentState.value
      })
    })
    filterTreeData.value = stateDate
    setDefaultSelectedNode()
  }

  // 切换店铺
  function changeShop() {
    advertStore.changeShop({
      ...shopInfo.value,
      shopId: shopInfo.value.id,
    })
    advertStore.changeGroup({})
    advertStore.changeCampaignIn({})
    advertStore.changeCurrentLevel('campaign')
    getMenuList()
  }
  // 设置默认选中节点
  function setDefaultSelectedNode() {
    if (!filterTreeData.value.length) return
    let currentLevel = advertStore.currentLevel
    let campaignId = advertStore.currentCampaign?.campaignId
    // 未选中广告的时候默认第一个
    if (!campaignId) {
      currentState.value = 'enabled'
      let firstNode = filterTreeData.value?.[0]
      selectedKeys.value = [firstNode.key]
      chooseNode(selectedKeys.value, firstNode)
      return
    }
    // 高亮节点
    let currentNode: any = {}
    filterTreeData.value.forEach((item: any) => {
      if (item.key == campaignId + currentState.value) {
        currentState.value = currentState.value.toLowerCase()
        currentNode = item
      }
    })

    if (currentLevel === 'campaign') {
      selectedKeys.value = [currentNode?.key]
    } else {
      expandedKeys.value.push(currentNode?.key)
      selectedKeys.value = [advertStore.currentGroup?.adGroupId + currentNode?.key]
    }
  }

  // 获取店铺
  async function getShopList() {
    const res: any = await findShopMarketByParam()
    originShopList.value = res?.data || []
    shopInfo.value = originShopList.value.find((el: any) => el.id === advertStore.currentShop?.shopId)
    if (shopInfo.value) {
      advertStore.changeShop({
        ...shopInfo.value,
        shopId: shopInfo.value.id,
      })
    }
    handleSearch()
  }
  // 店铺选择
  function handleSearch(val?: string) {
    shopList.value = []
    shopLoading.value = true
    if (!val) {
      shopList.value = originShopList.value.slice(0, 50)
      if (!shopList.value.find((el: any) => el.id === shopInfo.value.id)) {
        shopList.value.push(shopInfo.value)
      }
    } else {
      let filterArr = originShopList.value.filter((el: any) => el.shopName.indexOf(val) > -1)
      shopList.value = filterArr.slice(0, 50)
    }
    window.setTimeout(() => {
      shopLoading.value = false
    }, 100)
  }
  // 返回广告活动
  function toBackCampaign() {
    router.replace('/advert/campaign/campaignManagement')
    visitedRouteStore.removeVisitedRoute(route)
  }
  // 返回广告组详情
  function toBackGroup() {
    advertStore.changeCurrentLevel('campaign')
    advertStore.changeGroup({})
    setDefaultSelectedNode()
  }

  // 进入编辑页面
  function openCreatePage() {
    advertStore.changeDarftInfo({})
    router.push('/advert/campaign/createSpCampaign')
  }
  // 打开编辑广告活动
  function openEditDialog(row: any) {
    currentNode.value = row
    showEditDialog.value = true
  }
  // 选中节点
  function chooseNode(selectedKeys: Array<string | number>, data: any) {
    let _data = data?.node || data
    showDetail.value = false
    advertStore.changeCampaignIn({
      adType: 'SPONSORED_PRODUCTS',
      campaignId: _data.campaignId,
      campaignName: _data.campaignName,
      targetingType: _data.targetingType,
    })
    setCurrentTabName(_data)
    setTimeout(() => {
      showDetail.value = true
    }, 50)
  }

  function setCurrentTabName(_data: any) {
    if (_data.level === 2) {
      advertStore.changeCurrentLevel('campaign')
      advertStore.changeGroup({})
    } else if (_data.level === 3) {
      advertStore.changeCurrentLevel('adGroup')
      advertStore.changeGroup({
        adGroupId: _data.adGroupId,
        adGroupName: _data.adGroupName,
      })
    }
    let defaultName = _data.level === 2 ? 'adGroup' : 'product'

    if (_data.adType == 'SPONSORED_DISPLAY' && activeTabName.value == 'placement') {
      activeTabName.value = defaultName
    } else if ((_data.adType == 'SPONSORED_DISPLAY' || _data.targetingType == 'AUTO') && activeTabName.value == 'keyword') {
      activeTabName.value = defaultName
    } else if ((_data.adType != 'SPONSORED_PRODUCTS' || _data.targetingType != 'AUTO') && activeTabName.value == 'targeting') {
      activeTabName.value = defaultName
    }
  }

  watch(currentLevel, () => {
    activeTabName.value = currentLevel.value === 'campaign' ? 'adGroup' : 'product'
  })
</script>
<style lang="less" scoped>
  .advert-detail-wrap {
    height: 100%;
  }
  .arco-tabs {
    background-color: #fff;
  }
  :deep(.arco-virtual-list) {
    &:hover {
      &::-webkit-scrollbar-thumb {
        background-color: var(--color-neutral-4);
      }
    }
    scrollbar-color: transparent transparent;
    scrollbar-track-color: transparent;
    -ms-scrollbar-track-color: transparent;
    /* 滚动条宽度 */
    &::-webkit-scrollbar {
      width: 9px;
      height: 9px;
    }
    /* 滚动条的滑块 */
    &::-webkit-scrollbar-thumb {
      background-color: transparent;
      border-radius: 6px;
    }
  }

  .menu-list {
    width: auto;
    min-width: 280px;
    border-right: 1px solid var(--color-border);
    .shop-w {
      padding: 10px;
      border-bottom: 1px solid var(--color-border);
    }
    .menu-header {
      padding: 10px;
      .title {
        font-weight: bold;
      }
    }
    .menu-edit {
      position: absolute;
      right: 8px;
      font-size: 12px;
      top: 10px;
      color: #3370ff;
      display: none;
    }
  }
  :deep(.arco-tree-node) {
    &:hover {
      .menu-edit {
        display: block;
      }
    }
  }
  :deep(.arco-tree-node-disabled-selectable .arco-tree-node-title) {
    color: #999;
  }
  .tree-name {
    font-size: 12px;
    padding-right: 15px;
  }
  .back-link {
    font-size: 12px;
    margin-bottom: 5px;
    cursor: pointer;
    color: #666;
  }
</style>
